package com.example.springboot.mqtt.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.*;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.sax.handler.RowHandler;
import com.baidu.aip.http.Headers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.springboot.mqtt.config.RedisConfig;
import com.example.springboot.mqtt.entity.*;
import com.example.springboot.mqtt.serivice.*;
import com.example.springboot.mqtt.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IVehicleHistrack24Service vehicleHistrack24Service;

//    @GetMapping("/ocr")
//    public void test() throws MalformedURLException {
//        BufferedImage image = null;
//        try {
////            image = ImageIO.read(new URL("http://static8.ziroom.com/phoenix/pc/images/price/aacd14fbc53a106c7f0f0d667535683as.png"));
//            File imageFile = new File("src/main/resources/lottery/123.jpg");
//            ITesseract instance = new Tesseract();
//            instance.setDatapath("src/main/resources/tessdata/language/");
//            instance.setLanguage("eng");
//            String ocr = instance.doOCR(imageFile);
//            System.out.println("ocr result : " + ocr);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }

//    @GetMapping("/get_order_info")
//    @Scheduled(cron = "* 0/30 * * * ?")
//    public void getOrderInfo(){
//        for (int i = 1; i < 2; i++) {
//            try {
//                Thread.sleep(3000);
//
//                String url = "https://channels.weixin.qq.com/shop-faas/mmchannelstradeorder/cgi/getList?token=1992790947&lang=zh_CN&pageNum="+i+"&nextKey=&orderStatus=-1";
//
//                String body = HttpRequest.get(url)
//                        .header("Cookie", "logTrackKey=4b399c5f71404b6ea1dac5bfa40ada26; secToken=6088045f75fe4d9aee13dfb44438b320; qm_authimgs_id=0; fqm_sessionid=3f4c436b-4132-451a-8ae0-44d2888d982a; qq_domain_video_guid_verify=f0c810dbb614029d; video_omgid=f0c810dbb614029d; skey=@bkQUYX8v0; uin=o37054688; verifysession=h01d22415c63beb928b7429ed5ac3aa10c4ff5f10f84e76c0a3af4bdc58384089631ed6bddea9232c0f; login_type=wxqrcode; bizuin=3851896409; slave_user=gh_de7f06731f2a; slave_bizuin=3851896409; data_bizuin=3851896409; sessionid=BgAAW6ENBPIkLgy1f0HaT1iHA9s9G6zOlnclyQ%2FeIuI6wNr72OnSsEu1CjEOTK4kP5fxIwctFzdi9x9QpJF%2FBFqgJYxbz0cfbkA%3D; wxuin=251668726; qm_verifyimagesession=h013e2dd78f0e7c1054f41cda889dfcaf31407cc60cc09c70c8c41143851bc645c27c7684deeb3433b5; _clck=3882875246|1|fgv|0; biz_token=b_0000018b_fb9b3c81_0c16d17e_1cf3306b_aec2c0bb; biz_ticket=gidBujo6ygDW50sBN/8DtmVfAAAAAAAAAAAAAAAAAAA=; biz_magic=4248642c9672f3dc8c2d38756eadc4970e23b354339351f04c63dafc5edc54f4; biz_rand=CAESIEbHeoe/D3J0zmcnE7L7x1V03syIBKT4AEYDVYlXCd6V; data_ticket=gifUoBGTg7vLOXahwUOWKGeDAwFPHbuUEzWceL89u7s=; slave_sid=Nkp1QzU1UW4zcVhSbE12U1hCME1EOTI0ZmViY01qT1hoWnllVXBINmdDWW1jUVFQWmtWcEIxZ1FxdjEzcVN5d1JyQlo1ZW0zcWNWdEFIa0dRVU8wT2JUVFNfVkU0WEZEcWVhTnpVTzNIUnpfU2tjYTBkRHNlTHoza1Y4RDhaNGJqRUVzdmFqYURLVHZhU3Y5; rand_info=CAESIP/GPca/EyrD/hKNKXyiBy7hQekk/o/9InqWW4Sy49c6; data_token=1767437848")
//                        .execute().body();
//                JSONObject jsonObject = JSONUtil.parseObj(body);
//                if ((boolean) jsonObject.get("success")) {
//                    Object o = jsonObject.get("orders");
//                    JSONArray orderArray = JSONUtil.parseArray(o);
//                    for (Object order : orderArray) {
//                        JSONObject orderObject = JSONUtil.parseObj(order);
//                        Object orderId = orderObject.get("orderId");
//
//                        Object orderInfoObject = orderObject.get("orderInfo");
//                        JSONObject orderIObject = JSONUtil.parseObj(orderInfoObject);
//                        Object deliveryInfo = orderIObject.get("deliveryInfo");
//                        JSONObject deliveryObject = JSONUtil.parseObj(deliveryInfo);
//                        Object addressInfo = deliveryObject.get("addressInfo");
//                        OrderInfo orderInfo = JSONUtil.toBean(addressInfo.toString(), OrderInfo.class);
//                        orderInfo.setOrderId(orderId.toString());
//
//                        LambdaQueryWrapper<OrderInfo> orderQuery = new LambdaQueryWrapper<>();
//                        orderQuery.eq(OrderInfo::getOrderId, orderId);
//                        OrderInfo info = orderInfoService.getOne(orderQuery);
//                        System.out.println(info);
//                        if (info != null) {
//                            orderInfoService.update(orderInfo, orderQuery);
//                        } else {
//                            orderInfoService.save(orderInfo);
//                        }
//                    }
////                    return new R(true, "success");
//                } else {
////                    return new R(false, "请登录");
//                    log.error("请登录");
//                }
//            } catch (Exception e) {
////                return new ProjectExceptionAdvice().doException(e);
//            }
//        }
//    }

    @GetMapping("/update_histrack")
    public void updateHistrack(@RequestParam("ids") String ids,Long realId) {
        VehicleHistrack24 realInfo = vehicleHistrack24Service.getById(realId);
        if(realInfo == null){
            log.error("realInfo is null");
            return;
        }
        if (StringUtils.isNotBlank(ids)) {
            String[] idArray = ids.split(",");
            for (String id : idArray) {
                VehicleHistrack24 histrack = vehicleHistrack24Service.getById(id);
                if(histrack!= null){
                    histrack.setJsonData(realInfo.getJsonData());

                    vehicleHistrack24Service.updateById(histrack);
                }else{
                    VehicleHistrack24 vehicleHistrack24 = BeanUtil.copyProperties(realInfo, VehicleHistrack24.class);
                    vehicleHistrack24.setId(Long.valueOf(id));
                    vehicleHistrack24Service.save(vehicleHistrack24);
                }
            }
        }
    }

    @GetMapping("/get_cookie")
    public void getCookie() {
        String url = "https://www.cwl.gov.cn/ygkj/wqkjgg/ssq/";
        HttpResponse res = HttpRequest.get(url)
                .header(Headers.USER_AGENT,"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36")
                .execute();
        System.out.println(res);
        System.out.println(res.getCookies());
        System.out.println(res.getCookieStr());
    }

    @GetMapping("/test")
    public void test(@RequestParam("keyword") String keyword){
        String url = "http://localhost:7001/?email=sallie1589@v8v6.cse445.com&password=huangkai841005";
        String body = HttpRequest.get(url)
                .header(Headers.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36")
                .header("X-Requested-With", "XMLHttpRequest")
                .header(Header.COOKIE, "BIDUPSID=457C3455302D430C9674CAC89AF78CFA; PSTM=1657781295; BAIDUID=CE87CE2967A79BC2C0617B8BA1AC45B3:SL=0:NR=10:FG=1; BD_UPN=12314753; MCITY=-176%3A; H_WISE_SIDS_BFESS=234020_216839_213354_214792_110085_244727_259031_261710_236312_256419_265881_266354_265615_267074_268405_268593_266186_259642_269232_269783_268236_269905_267066_256739_270460_270519_270603_270547_271019_271173_256958_267659_271319_270102_271879_269857_271813_271935_234296_234208_269296_272082_272226_270055_272279_267596_272336_253022_272653_272836_260335_272986_273061_267558_273160_273164_273138_273215_273263_273238_273301_273400_273392_271158_273455_273473_273519_271562_271146_273703_273318_264170_272262_263619_274082_273931_273965_274142_269610_273918_273044_273598_272695_272859_256223_272562_274426_274441_188333_274649_274765_274759_274822_274839_274844_274856_274847_270158_274870_273981_275070_272801_274452_267807_267547_275145_272333_275167_275197_275147_272318_8000051_8000108_8000124_8000142_8000160_8000162_8000165_8000170_8000183_8000186_8000204; sug=3; sugstore=0; ORIGIN=0; bdime=0; ispeed_lsm=2; H_WISE_SIDS=39635_39668_39672_39664_39676_39679_39712_39751_39766_39791_39704_39688; BDUSS=lJMeHZRYmRpSXE0UGp6dk5USW5RaXd2VXRYcFNrVFFzUk5SeEh1aEtYaVd0WUpsRVFBQUFBJCQAAAAAAAAAAAEAAACfa9v~c3hsYW94aWFuZwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJYoW2WWKFtlf; BDUSS_BFESS=lJMeHZRYmRpSXE0UGp6dk5USW5RaXd2VXRYcFNrVFFzUk5SeEh1aEtYaVd0WUpsRVFBQUFBJCQAAAAAAAAAAAEAAACfa9v~c3hsYW94aWFuZwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJYoW2WWKFtlf; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BDSFRCVID=5uIOJeC62mpfkbJqVZgnUAN5gSNgBovTH6aozrIKbiVyO4D2LviLEG0PFM8g0KFhOdh3ogKKyeOTHu8F_2uxOjjg8UtVJeC6EG0Ptf8g0x5; H_BDCLCKID_SF=Jn-O_C82JKL3HJOmMJjE5bcHMhoK--Q0KKJyLR-8Kb7VbPjoMUnkbfJBDGOUQbjkK56e2JRkQIbvennJhf6AXx47yajK2boGQG58-UbuQtoFDqrP0UjpQT8ryJ_OK5OiJgDqslnNab3vOPTNXpO15jkzBN5thURB2DkO-4bCWJ5TMl5jDh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KPkeaKvia-THBMb1fDnDBT5h2M4qMxtOLR3pWDTm_q5TtUJMeCnTDbAhe4tX-NFJJ5KtJx5; H_PS_645EC=2e7cTUbugOqhTVjLNzr5%2FDiuawzqN3FtHO%2Bk%2BIlcJWq46kZzYLKgFusysCA; COOKIE_SESSION=171_1_7_7_8_24_1_0_6_7_1_7_591_0_0_0_1700736994_1700706226_1700737162%7C9%23175549_11_1700706222%7C9; WWW_ST=1700737266076")
                .execute().body();
        System.out.println(body);
    }

    /**
     * 读取上传的excel文件内容
     */
    @PostMapping("/upload")
    public void upload(@RequestParam("file") MultipartFile file){
        String fileName = file.getOriginalFilename();
        if (fileName != null) {
            String suffix = fileName.substring(fileName.lastIndexOf("."));
        }
        String filePath = "F:\\test\\";
        File fileDir = new File(filePath);
        if (!fileDir.exists()){
            fileDir.mkdirs();
        }
        String filePathName = filePath + fileName;
        File filePathNameDir = new File(filePathName);
        String filePathName_p = filePath + "processed\\" + fileName;
        File filePathNameDir_p = new File(filePathName_p);
        if(filePathNameDir.exists() || filePathNameDir_p.exists()){
            System.out.println("文件："+filePathName+"已存在，请勿重复上传");
            return;
        }
        try {
            file.transferTo(new File(filePathName));
            //读取excel文件内容
            ExcelUtil.readBySax(filePathName, 0, createRowHandler());

        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/readExcle")
    public void readExcle(){
        File directory = new File("F:\\test\\"); // 指定目录的路径
        List<File> excelFiles = new ArrayList<>();
//        listExcelFiles(directory, excelFiles);
        File[] files = directory.listFiles();
        System.out.println(files);
        if (files != null) {
            for (File file : files) {
                if (!file.isDirectory()) {
                    if (file.getName().endsWith(".xls") || file.getName().endsWith(".xlsx")) {
                        excelFiles.add(file);
                    }
                }
            }
        }

        for (File file : excelFiles) {
            System.out.println(file.getName());
            // 在这里可以对Excel文件进行处理，比如读取内容等操作
            String fileName = file.getName();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String filePath = "F:\\test\\processed\\";
            File fileDir = new File(filePath);
            if (!fileDir.exists()){
                fileDir.mkdirs();
            }
            String filePathName = filePath + fileName;
            File filePathNameDir = new File(filePathName);
            if(filePathNameDir.exists()){
                System.out.println("文件："+fileName+"已存在，请勿重复上传");
                return;
            }
            file.renameTo(new File(filePathName));
            //读取excel文件内容
            ExcelUtil.readBySax(filePathName, 0, createRowHandler());

        }
    }

    public static void listExcelFiles(File directory, List<File> excelFiles) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    listExcelFiles(file, excelFiles); // 递归处理子目录
                } else if (file.getName().endsWith(".xls") || file.getName().endsWith(".xlsx")) {
                    excelFiles.add(file);
                }
            }
        }
    }

    private RowHandler createRowHandler() {
        return new RowHandler() {
            @Override
            public void handle(int sheetIndex, long rowIndex, List<Object> rowlist) {
                // 获取当前时间
                LocalDateTime now = LocalDateTime.now();
                // 定义时间的格式
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                // 格式化时间
                String formattedDateTime = now.format(formatter);

                String key = "data:list";
                StringBuilder sb = new StringBuilder();
                for (Object value : rowlist) {
                    if(value== null){
                        value = "NaN";
                    }
                    sb.append(value).append("##");
                }
                redisUtil.lSet(key,sb.toString());
                Console.log("[{}] [{}] {}", sheetIndex, rowIndex, rowlist);
            }
        };
    }
    @Autowired
    private IProductClassService productClassService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IStoreCityService storeCityService;
    @Autowired
    private IStoreOrderService storeOrderService;
    @GetMapping("/get_data")
    public void getDataFromRedis() {
        log.info("从redis的datalist列表中读取数据");
        try {
            while (true) {
                Object res = redisUtil.lPop("data:list");
                System.out.println(res);
                if (res != null) {
                    String[] arr = res.toString().split("##");
                    if (arr[0].equals("二级类（品类）")) continue;
                    for (int i = 0; i < arr.length; i++) {
                        if (arr[i].equals("NaN")) {
                            arr[i] = "0";
                        }
                    }
                    //商品分类id
                    long productClassId = 0L;
                    if (arr[0] != null && !arr[0].equals("NaN")) {
                        ProductClass productClassInfo = productClassService.getOne(new LambdaQueryWrapper<ProductClass>().eq(ProductClass::getCode, arr[0]));
                        if (productClassInfo == null) {
                            ProductClass productClass = new ProductClass();
                            productClass.setId(IdUtil.getSnowflake().nextId());
                            productClass.setCode(arr[0]);
                            productClass.setClassName(arr[1]);
                            productClassService.save(productClass);
                            productClassId = productClass.getId();
                        } else {
                            productClassId = productClassInfo.getId();
                        }
                    }

                    //商品id
                    long productId = 0L;
                    if (arr[2] != null && !arr[2].equals("NaN")) {
                        Product productInfo = productService.getOne(new LambdaQueryWrapper<Product>().eq(Product::getCode, arr[2]));
                        if (productInfo == null) {
                            Product product = new Product();
                            product.setId(IdUtil.getSnowflake().nextId());
                            product.setCode(arr[2]);
                            product.setProductName(arr[3]);
                            productService.save(product);
                            productId = product.getId();
                        } else {
                            productId = productInfo.getId();
                        }
                    }

                    //便利店所属市id
                    long storeCityId = 0L;
                    if (arr[4] != null && !arr[4].equals("NaN")) {
                        StoreCity storeCityInfo = storeCityService.getOne(new LambdaQueryWrapper<StoreCity>().eq(StoreCity::getCityName, arr[4]));
                        if (storeCityInfo == null) {
                            StoreCity storeCity = new StoreCity();
                            storeCity.setId(IdUtil.getSnowflake().nextId());
                            storeCity.setCityName(arr[4]);
                            storeCityService.save(storeCity);
                            storeCityId = storeCity.getId();
                        } else {
                            storeCityId = storeCityInfo.getId();
                        }
                    }

                    //便利店id
                    long storeId = 0L;
                    if (arr[5] != null && !arr[5].equals("NaN") && !arr[5].equals("结果")) {
                        Store storeInfo = storeService.getOne(new LambdaQueryWrapper<Store>().eq(Store::getCode, arr[5]));
                        if (storeInfo == null) {
                            Store store = new Store();
                            store.setId(IdUtil.getSnowflake().nextId());
                            store.setCode(arr[5]);
                            store.setStoreName(arr[6]);
                            storeService.save(store);
                            storeId = store.getId();
                        } else {
                            storeId = storeInfo.getId();
                        }
                    }

                    //写入订单信息
                    /**
                     * 1、如果表中库存数量和金额跟数据不一致，则直接写入订单表
                     * 2、如果库存数量和金额都为0，则直接写入订单表
                     * 3、库存数量 = 购进数量+配送数量-退货数量-销售数量+调入数量-调出数量+盘盈数量-盘亏数量-报废数量
                     * 4、金额 = 购进金额+配送金额-退货金额-销售金额+调入金额-调出金额+盘盈金额-盘亏金额-报废金额
                     * 5、写入销售成本、销售收入
                     * 6、结合商品分类id、商品id、便利店所属市id、便利店id和订单数据写入订单表
                     */
                    //查询订单表中分类id、商品id和便利店所属市id、便利店id是否存在
                    StoreOrder orderInfo = storeOrderService.getOne(new LambdaQueryWrapper<StoreOrder>()
                            .eq(StoreOrder::getProductId, productId)
                            .eq(StoreOrder::getStoreCityId, storeCityId)
                            .eq(StoreOrder::getStoreId, storeId)
                            .orderByDesc(StoreOrder::getCreateTime)
                            .last("limit 1")
                    );
                    //1、如果表中库存数量和金额跟数据不一致，则直接写入订单表
                    int count = 0;
                    double price = 0;
                    int type = 0;
                    if (orderInfo != null) {
                        if (orderInfo.getCount()== Integer.parseInt(arr[30]) && orderInfo.getPrice()== Double.parseDouble(arr[31])
                                && orderInfo.getSalesCost()== Double.parseDouble(arr[18]) && orderInfo.getSalesIncome()== Double.parseDouble(arr[19])){
                            log.error(orderInfo.getId() + "重复数据！");
                            continue;
                        }
                        //判断库存数量与金额是否一致
                        if (orderInfo.getCount() != Integer.parseInt(arr[8]) || orderInfo.getPrice() != Double.parseDouble(arr[9])) {
                            log.error(orderInfo.getCount() + " - " + Integer.parseInt(arr[8]));
                            log.error(orderInfo.getPrice() + " - " + Double.parseDouble(arr[9]));
                            log.error(orderInfo.getId() + "期初库存数量或期初库存价值异常！");
                            //重新写回redis缓存
                            redisUtil.lSet("data:error",res);
                            continue;
                        }
                        // 3、库存数量 = 期初库存数量+购进数量+配送数量-退货数量-销售数量+调入数量-调出数量+盘盈数量-盘亏数量-报废数量
                        count = orderInfo.getCount() + Math.abs(Integer.parseInt(arr[10])) + Math.abs(Integer.parseInt(arr[12])) - Math.abs(Integer.parseInt(arr[14])) - Math.abs(Integer.parseInt(arr[16])) + Math.abs(Integer.parseInt(arr[20])) - Math.abs(Integer.parseInt(arr[22])) + Math.abs(Integer.parseInt(arr[24])) - Math.abs(Integer.parseInt(arr[26])) - Math.abs(Integer.parseInt(arr[28]));
                        //4、金额 = 期初库存价值+购进金额+配送金额-退货金额-销售金额+调入金额-调出金额+盘盈金额-盘亏金额-报废金额
                        price = orderInfo.getPrice() + Math.abs(Double.parseDouble(arr[11])) + Math.abs(Double.parseDouble(arr[13])) - Math.abs(Double.parseDouble(arr[15])) - Math.abs(Double.parseDouble(arr[18])) + Math.abs(Double.parseDouble(arr[21])) - Math.abs(Double.parseDouble(arr[23])) + Math.abs(Double.parseDouble(arr[25])) - Math.abs(Double.parseDouble(arr[27])) - Math.abs(Double.parseDouble(arr[29]));
                        //四舍五入，保留小数点后两位
                        price = new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        //判断期末库存数量与金额是否一致
                        if (count != Integer.parseInt(arr[30]) || price != Double.parseDouble(arr[31])) {
                            log.error(count + " - " + Integer.parseInt(arr[30]));
                            log.error(price + " - " + Double.parseDouble(arr[31]));
                            log.error(orderInfo.getId() + "期末库存数量或期末库存价值异常！");
                            //重新写回redis缓存
                            redisUtil.lSet("data:error",res);
                            continue;
                        }
                    } else {
                        // 3、库存数量 = 期初库存数量+购进数量+配送数量-退货数量-销售数量+调入数量-调出数量+盘盈数量-盘亏数量-报废数量
                        count = Math.abs(Integer.parseInt(arr[8])) + Math.abs(Integer.parseInt(arr[10])) + Math.abs(Integer.parseInt(arr[12])) - Math.abs(Integer.parseInt(arr[14])) - Math.abs(Integer.parseInt(arr[16])) + Math.abs(Integer.parseInt(arr[20])) - Math.abs(Integer.parseInt(arr[22])) + Math.abs(Integer.parseInt(arr[24])) - Math.abs(Integer.parseInt(arr[26])) - Math.abs(Integer.parseInt(arr[28]));
                        //4、金额 = 期初库存价值+购进金额+配送金额-退货金额-销售金额+调入金额-调出金额+盘盈金额-盘亏金额-报废金额
                        price = Math.abs(Double.parseDouble(arr[9])) + Math.abs(Double.parseDouble(arr[11])) + Math.abs(Double.parseDouble(arr[13])) - Math.abs(Double.parseDouble(arr[15])) - Math.abs(Double.parseDouble(arr[18])) + Math.abs(Double.parseDouble(arr[21])) - Math.abs(Double.parseDouble(arr[23])) + Math.abs(Double.parseDouble(arr[25])) - Math.abs(Double.parseDouble(arr[27])) - Math.abs(Double.parseDouble(arr[29]));
                        //判断期末库存数量与金额是否一致
                        //四舍五入，保留小数点后两位
                        price = new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        if (count != Integer.parseInt(arr[30]) || price != Double.parseDouble(arr[31])) {
                            log.error(count + " - " + Integer.parseInt(arr[30]));
                            log.error(price + " - " + Double.parseDouble(arr[31]));
                            log.error("期末库存数量或期末库存价值异常！- 商品id:" + productId + " 城市id:" + storeCityId + " 便利店id:" + storeId);
                            //重新写回redis缓存
                            redisUtil.lSet("data:error",res);
                            continue;
                        }
                    }


                    StoreOrder storeOrder = new StoreOrder();
                    storeOrder.setId(IdUtil.getSnowflake().nextId());
                    storeOrder.setProductId(productId);
                    storeOrder.setStoreCityId(storeCityId);
                    storeOrder.setStoreId(storeId);
                    storeOrder.setType(type);
                    storeOrder.setCount(count);
                    storeOrder.setPrice(price);
                    //5、写入销售成本、销售收入
                    storeOrder.setSalesCost(Double.parseDouble(arr[18]));
                    storeOrder.setSalesIncome(Double.parseDouble(arr[19]));
                    storeOrder.setCreateTime(new Date());
                    System.out.println(storeOrder);
                    storeOrderService.save(storeOrder);
                } else {
                    return;
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }


}